package com.liruo.treasureattic.autoconfiguration.mybatis;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.util.Date;

public class DateTypeHandler extends BaseTypeHandler<Date> {
    private final boolean isMillis;
    public DateTypeHandler() {
        this.isMillis = true;
    }
    public DateTypeHandler(boolean isMillis) {
        this.isMillis = isMillis;
    }
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        Instant instant = parameter.toInstant();
        long val = this.isMillis ? instant.toEpochMilli()  :instant.getEpochSecond();
        ps.setLong(i, val);
    }

    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long val = rs.getLong(columnName);
        return val > 0 ? new Date(val) : null;
    }

    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long val = rs.getLong(columnIndex);
        return val > 0 ? new Date(val) : null;
    }

    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long val = cs.getLong(columnIndex);
        return val > 0 ? new Date(val) : null;
    }
}